package moduloInterface;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import moduloAluno.Aluno;
import moduloAluno.ConjuntoAluno;
import moduloAluno.IOAluno;
import moduloConhecimento.Conhecimento;
import moduloConhecimento.MapeamentoTeclado;
import moduloConhecimento.nivel.RepositorioNiveis;
import moduloControle.Controle;
import moduloTutor.Tutor;
import util.Constantes;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class Usuario extends javax.swing.JDialog {
	private JPanel jPanel1;
	private JLabel jLabel2Cpf;
	private JComboBox jComboBox1;
	private JPanel jPanel2;
	private JButton jButtonCadastrar;
	private JButton jButtonCancelar;
	private JButton jButtonOk;
	private JList jListAlunos;
	private JTextField jTextFieldIdade;
	private JTextField jTextFieldCpf;
	private JTextField jTextFieldNome;
	private JLabel jLabelIdade;
	private JLabel jLabel1;
	private DefaultListModel listModelUsuarios = null;
	private DefaultComboBoxModel jListAlunosModel;
	private ConjuntoAluno	alunos;
	private IOAluno	file;
	private Controle controle;
	private String[] listaTeclados;

	/**
	* Auto-generated main method to display this JDialog
	*/
	
	/*
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				JFrame frame = new JFrame();
				Usuario inst = new Usuario(frame);
				inst.setVisible(true);
			}
		});
	}
	*/
	
	public Usuario(JFrame frame,boolean travado, Controle controle) {
		super(frame,travado);
		//this.setLocationRelativeTo(frame);
		//this.setResizable(false);
		//this.setVisible(true);
		alunos = new ConjuntoAluno();
		this.controle = controle;
		listaTeclados = getListaTeclados();
		
		file = new IOAluno();
		try {
			file.mapearArquivoLeitura(Constantes.CAMINHO_ARQ_ALUNOS);
			file.carregarAlunosDoArquivo(alunos);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		initGUI();
		
		getContentPane().setLayout(null);
		{
			jPanel1 = new JPanel();
			getContentPane().add(jPanel1);
			jPanel1.setBounds(165, 12, 215, 93);
			jPanel1.setLayout(null);
			jPanel1.setBorder(BorderFactory.createTitledBorder(""));
			{
				jLabel1 = new JLabel();
				jPanel1.add(jLabel1);
				jLabel1.setText("Nome:");
				jLabel1.setBounds(12, 5, 86, 34);
			}
			{
				jLabel2Cpf = new JLabel();
				jPanel1.add(jLabel2Cpf);
				jLabel2Cpf.setText("Cpf");
				jLabel2Cpf.setBounds(16, 37, 20, 14);
			}
			{
				jLabelIdade = new JLabel();
				jPanel1.add(jLabelIdade);
				jLabelIdade.setText("Idade");
				jLabelIdade.setBounds(142, 37, 32, 15);
			}
			{
				jTextFieldNome = new JTextField();
				jPanel1.add(jTextFieldNome);
				jTextFieldNome.setBounds(55, 12, 145, 19);
			}
			{
				jTextFieldCpf = new JTextField();
				jPanel1.add(jTextFieldCpf);
				jTextFieldCpf.setBounds(54, 34, 81, 21);
			}
			{
				jTextFieldIdade = new JTextField();
				jPanel1.add(jTextFieldIdade);
				jTextFieldIdade.setBounds(174, 34, 25, 21);
			}
			{
				jButtonCadastrar = new JButton();
				jPanel1.add(jButtonCadastrar);
				jButtonCadastrar.setText("Cadastrar");
				jButtonCadastrar.setBounds(66, 67, 100, 18);
				jButtonCadastrar.setBackground(new java.awt.Color(107,150,220));
				jButtonCadastrar.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(0,0,0)));
				jButtonCadastrar.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						//System.out.println("jButtonCadastrar.actionPerformed, event="+evt);
						cadastrarAluno();
						//TODO add your code for jButtonCadastrar.actionPerformed
					}
				});
			}
		}
		{
			jListAlunosModel = 	new DefaultComboBoxModel();
			jListAlunos = new JList();
			getContentPane().add(jListAlunos);
			jListAlunos.setModel(jListAlunosModel);
			jListAlunos.setBounds(25, 12, 117, 172);
			jListAlunos.setBorder(BorderFactory.createTitledBorder(""));
			// jListAlunosModel)setModel(getListModelUsuarios());
			jListAlunos.addListSelectionListener(new ListSelectionListener() {
				public void valueChanged(ListSelectionEvent evt) {
					//System.out.println("jListAlunos.valueChanged, event="+evt);
					//TODO add your code for jListAlunos.valueChanged
				}
			});
		}
		{
			jButtonOk = new JButton();
			getContentPane().add(jButtonOk);
			jButtonOk.setText("Ok");
			jButtonOk.setBounds(165, 166, 106, 18);
			jButtonOk.setBackground(new java.awt.Color(107,150,220));
			jButtonOk.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(0,0,0)));
			jButtonOk.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent evt) {
					verificaOk();
					//System.out.println("jButtonOk.actionPerformed, event="+evt);
					//TODO add your code for jButtonOk.actionPerformed
				}
			});
		}
		{
			jButtonCancelar = new JButton();
			getContentPane().add(jButtonCancelar);
			getContentPane().add(getJPanel2());
			jButtonCancelar.setText("Cancelar");
			jButtonCancelar.setBounds(274, 166, 106, 18);
			jButtonCancelar.setBackground(new java.awt.Color(107,150,220));
			jButtonCancelar.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(0,0,0)));
			jButtonCancelar.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent evt) {
					dispose();
					//System.out.println("jButtonCancelar.actionPerformed, event="+evt);
					//TODO add your code for jButtonCancelar.actionPerformed
				}
			});
		}
		carregaJList();
	}
	
	private String[] getListaTeclados()
	{
		File dir = new File(Constantes.CAMINHO_TECLADOS);
		FileFilter filtro = new FileFilter()
		{
			public boolean accept(File dir)
			{
				return(dir.isDirectory());
			}
		};
		int tamanho, j;
		File[] subDirs = dir.listFiles(filtro);
		tamanho = subDirs.length;
		String[] subDirsStr = new String[tamanho];
		String[] subDirStr2;
		for (int i = 0; i < subDirs.length; i++)
			subDirsStr[i] = subDirs[i].toString().substring(Constantes.CAMINHO_TECLADOS.length());
		
		for (int i = 0; i < subDirsStr.length; i++)
			if (subDirsStr[i].charAt(0) == '.')
			{
				tamanho--;
				subDirsStr[i] = null;
			}
		
		subDirStr2 = new String[tamanho];
		j=0;
		for (int i = 0; i < subDirsStr.length; i++)
			if (subDirsStr[i] != null)
				subDirStr2[j++] = subDirsStr[i]; 
				
		return(subDirStr2);
		
	}
	
	private void carregaJList(){
			
		for (int i=0; i < alunos.getLength(); i++){
				
			if(alunos.getAlunos()[i]!= null ){
				//System.out.println("tem aluno");
				jListAlunosModel.addElement(alunos.getAlunos()[i].getNome());
			}
		}
			
	}
	
	private void initGUI() {
		try {
			this.setSize(400, 223);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void verificaOk(){
		//Object [] usuarios =  listModelUsuarios.toArray();
		int alunosSelecionados[] = jListAlunos.getSelectedIndices();
		String tecladoSelecionado;
		
		if (alunosSelecionados.length > 1)
		{		
			JOptionPane.showMessageDialog(this,
					"Selecione apenas um aluno por favor.");
		}
		
		else if (alunosSelecionados.length == 0){
			JOptionPane.showMessageDialog(this, "Selecione um aluno por favor");
		}
		
		else{
			jListAlunos.setSelectedIndex(alunosSelecionados[0]);
			String nome =  (String) jListAlunos.getSelectedValue();
			//System.out.println("nome = " + nome);
			Aluno arrayAlunos[] = alunos.getAlunos();
			//System.out.println("primeiro nome = " + arrayAlunos[0].getNome());
			Aluno alunoEscolhido = null;
			for (Aluno a : arrayAlunos){
				
				if(a != null){
					if (nome.equals(a.getNome())){
					alunoEscolhido = a;
					}
				}	
			}
			tecladoSelecionado = Constantes.RAIZ_ARQUIVOS + "/" 
							+ Constantes.CAMINHO_TECLADOS + (String)jComboBox1.getSelectedItem() + "/";
			try
			{
				controle.iniciarModulos(tecladoSelecionado);
			}
			catch (IOException e1)
			{
				throw new RuntimeException("Arquivos de configuracao do teclado faltando, erro fatal!");
			}
			controle.setAluno(alunoEscolhido);
			
			/*controle.setAluno(alunoEscolhido);
			controle.setConhecimento()*/
			
			try {
				file.mapearArquivoEscrita(Constantes.CAMINHO_ARQ_ALUNOS);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			file.salvarAlunosNoArquivo(alunos);
			file.fecharArquivoEscrita();
			
			dispose();
		}
		
	}
	
	private void cadastrarAluno(){
		int nivel = 1;
		if (jTextFieldNome.getText().equals("")){
			JOptionPane.showMessageDialog(this, "nome de usuario invalido");
		}
		else{
			Aluno aluno = new Aluno(jTextFieldNome.getText(), Integer.parseInt(jTextFieldIdade.getText()),jTextFieldCpf.getText(),nivel);
			jListAlunosModel.addElement(jTextFieldNome.getText());
			alunos.inserirAluno(aluno);
			jTextFieldNome.setText("");
			jTextFieldCpf.setText("");
			jTextFieldIdade.setText("");
		//	jListAlunos.add(jTextFieldNome.getText());
		}
	}
	
	private DefaultListModel getListModelUsuarios()
	{
		if (listModelUsuarios == null)
		{
			listModelUsuarios = new DefaultListModel();
		}
		return listModelUsuarios;
	}

	private JPanel getJPanel2() {
		if(jPanel2 == null) {
			jPanel2 = new JPanel();
			jPanel2.setBounds(165, 111, 215, 49);
			jPanel2.setBorder(BorderFactory.createTitledBorder(null, "Escolha o teclado", TitledBorder.LEADING, TitledBorder.TOP));
			jPanel2.setFont(new java.awt.Font("Tahoma",0,12));
			jPanel2.setLayout(null);
			jPanel2.add(getJComboBox1());
		}
		return jPanel2;
	}
	
	private JComboBox getJComboBox1() {
		if(jComboBox1 == null) {
			ComboBoxModel jComboBox1Model = 
				new DefaultComboBoxModel(listaTeclados);
						//new String[] { "Item One", "Item Two" });
			jComboBox1 = new JComboBox();
			jComboBox1.setModel(jComboBox1Model);
			jComboBox1.setBounds(17, 19, 181, 21);
		}
		return jComboBox1;
	}

}
